package org.lqq.serverRegisterAndFinder.eureka;

import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.appinfo.EurekaInstanceConfig;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.*;
import com.netflix.discovery.shared.Application;
import com.netflix.discovery.shared.Applications;
import org.lqq.config.ServerFinderAndRegisterConfig;
import org.lqq.serverRegisterAndFinder.ServerFinderAndRegister;
import org.lqq.serverRegisterAndFinder.serverFinder.eureka.ServerFinder;
import org.lqq.serverRegisterAndFinder.serverFinder.eureka.InstanceInfoFactory;
import org.lqq.serverRegisterAndFinder.serverFinder.eureka.MyEurekaClientConfig;
import org.lqq.serverRegisterAndFinder.serverFinder.eureka.MyEurekaInstaceConfig;
import org.lqq.serverRegisterAndFinder.serverRegister.eureka.EurekaServerRegister;

import java.util.List;

/**
 * Created by 李清泉 on 2017/10/26.
 *
 * @remark
 */
public class EurekaFactory {
    public static ServerFinderAndRegister create(ServerFinderAndRegisterConfig config) {

        //
        //最关键的代码，加载配置文件，向Eureka发送请求，获取服务列表。
        EurekaInstanceConfig eurekaInstaceConfig=new MyEurekaInstaceConfig();
        InstanceInfo instanceInfo = new InstanceInfoFactory().create(eurekaInstaceConfig);
        ApplicationInfoManager applicationInfoManager=new ApplicationInfoManager(eurekaInstaceConfig, instanceInfo);
        //DiscoveryManager.getInstance().initComponent(new MyDataCenterInstanceConfig(), new DefaultEurekaClientConfig());
        applicationInfoManager.setInstanceStatus(InstanceInfo.InstanceStatus.UP);
        applicationInfoManager.initComponent(eurekaInstaceConfig);
        EurekaClientConfig eurekaClientConfig=new MyEurekaClientConfig();
        //EurekaClient client = DiscoveryManager.getInstance().getEurekaClient();
        DiscoveryClient discoveryClient=new DiscoveryClient(applicationInfoManager,eurekaClientConfig,(AbstractDiscoveryClientOptionalArgs)null);
        ServerFinder serverFinder = new ServerFinder(discoveryClient);
        EurekaServerRegister register = new EurekaServerRegister(discoveryClient);
        Applications applications=discoveryClient.getApplications();
        List<Application> list= applications.getRegisteredApplications();
        for(Application application:list){
            System.out.println(application.getName());
            for(InstanceInfo info:application.getInstances()){
                System.out.println(info.getInstanceId());
                System.out.println(info.getHostName());
                System.out.println(info.getPort());
                System.out.println(info.getIPAddr());
            }

        }
        ServerFinderAndRegister eureka = new DefaultServerFinderAndRegister(serverFinder, register);
        return eureka;
    }
}
